<template>
  <el-dropdown
    ref="ref-el-dropdown"
    v-bind="props"
    v-on="events"
  >
    <span v-if="splitButton">
      {{ text }}
    </span>
    <el-button-package
      v-else-if="hasTrigger"
      :c-m="trigger"
    />
    <el-button v-else>
      {{ text }}
    </el-button>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item
        v-for="(item, index) in items"
        :key="buildDOMKey(item, index)"
        v-bind="item.props"
      >
        <span>{{ item.text }}</span>
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script lang="ts">
/*
prop 列表
  CM: ComponentModel  组件模型
CM.meta 扩展
  trigger: ComponentModel 触发按钮组件模型
            此扩展主要目的是保持按钮样式的灵活性，当前版本 split-button 模式，按钮只接收 type、size 两个按钮属性
            1. 如果设置了 split-button 模式，只会从 trigger 中取 text 作为按钮 title
            2. trigger 不支持 click 事件，即时添加了也无法在 el-dropdown 中触发
            3. trigger 未定义自动生成一个按钮，取 this.text 作为按钮 title
ref 列表
  ref-el-dropdown [默认]
*/
import { Component, Prop } from 'vue-property-decorator'
import TgComponent from '../TgComponent'
import { ComponentModel } from '@TG/interface'
import { isNotEmpty } from '@TG/kit/validate'
import ElButtonPackage from './ElButtonPackage.vue'

@Component({
  name: 'ElDropdownPackage',
  components: {
    ElButtonPackage
  }
})
export default class extends TgComponent {
  @Prop({ type: Object, required: true }) private CM!: ComponentModel

  get text() {
    return this.CM.meta?.trigger?.text || this.CM.text
  }

  get props() {
    const props: Map<string, any> = new Map<string, any>()
    const events = this.events
    if (events && events.click) {
      props.set('split-button', true)
    }
    return Object.assign(props, this.CM.props, this.$attrs)
  }

  get events() {
    return Object.assign({}, this.CM.events, this.$listeners)
  }

  get splitButton() {
    return this.props['split-button'] || false
  }

  get items() {
    return this.CM.items
  }

  get hasTrigger() {
    return isNotEmpty(this.CM.meta?.trigger)
  }

  get trigger() {
    return Object.assign({ text: this.text }, this.CM.meta?.trigger)
  }

  public defaultRef() {
    return 'el-dropdown'
  }
}
</script>
